#!/usr/bin/env python2
# coding: utf-8


import unittest
from zstack import Client
from zstack.controller import user

ADMIN_USERNAME = 'admin'
ADMIN_PASSWORD = 'password'
ZSTACK_API_URL = 'http://192.168.1.115:8080/zstack/api'


class TestUser(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        cls.client = Client(ADMIN_USERNAME, ADMIN_PASSWORD, ZSTACK_API_URL)
        cls.client.login()

    def test_create_update_delete_account(self):
        # 创建新账号，并验证用户名及密码
        new = user.create_account(self.client, 'py_create_username001', 'password')
        self.assertEqual(new['name'], 'py_create_username001')
        self.client.logout()  # 退出admin账号
        self.client = Client(new['name'], 'password', ZSTACK_API_URL)
        self.client.login()  # 登录新建账号
        self.client.logout()  # 退出新建账号

        # 在用户列表中查询该用户
        self.client = Client(ADMIN_USERNAME, ADMIN_PASSWORD, ZSTACK_API_URL)
        self.client.login()  # 登陆到管理员
        users = user.query_account(self.client)
        found = False
        for ur in users:
            if ur['uuid'] == new['uuid']:
                found = True
                break
        self.assertEqual(found, True)

        # 更改该用户的密码
        ur1 = user.update_account(self.client, new['uuid'], 'passwordModify')
        self.client.logout()  # 退出管理员
        self.client = Client(ur1['name'], 'passwordModify', ZSTACK_API_URL)
        self.client.login()  # 登录修改密码账号
        self.client.logout()  # 退出修改密码账号

        # 查询该用户
        self.client = Client(ADMIN_USERNAME, ADMIN_PASSWORD, ZSTACK_API_URL)
        self.client.login()  # 登陆到管理员
        ur2 = user.query_account_by_uuid(self.client, ur1['uuid'])
        self.assertIsNotNone(ur2)

        # 查询不存在的用户
        ur3 = user.query_account_by_uuid(self.client, 'not exist')
        self.assertEqual(ur3, [])

        # 删除该用户
        user.delete_account(self.client, new['uuid'])
        self.assertNotIn(new['uuid'], [ur.get('uuid') for ur in user.query_account(self.client)])


if __name__ == '__main__':
    unittest.main()
